<template>
  <el-dialog
    :title="id?'修改':'添加'"
    :visible.sync="dialogVisible"
    width="800px"
    :show="show"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open='open'>
    <el-form ref="form" :model="info" label-width="90px" :rules="rules"
             v-loading="infoLoading">
      <div class="el-dialog-div form-scrollbar">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="info.name"
                    placeholder="请填写名称" maxlength="255"/>
        </el-form-item>
        <el-form-item label="网址">
          <el-input type="text" v-model="info.url"
                    placeholder="请填写网址" maxlength="255"/>
        </el-form-item>
        <el-form-item label="类型" prop="from">
          <el-select
            :disabled="Boolean(this.id)"
            v-model="info.from"
            class="filter-left"
            placeholder="请选择类型"
            clearable
            filterable
            size="small"
          >
            <el-option v-for="item in fromOptions" :label="item.label" :disabled="item.disabled" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="来源">
          <el-select
            v-model="info.sourceId"
            class="filter-left"
            placeholder="请选择来源"
            clearable
            filterable
            size="small"
          >
            <el-option v-for="item in sourceOptions" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分组">
          <el-select
            v-model="info.diyGroupId"
            class="filter-left"
            placeholder="请选择分组"
            clearable
            filterable
            size="small"
          >
            <el-option v-for="item in groupOptions" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="info.desc" :rows="6"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo()">保存</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">取消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import {createBlock, getBlock, updateBlock} from "@/api/customer/block";
import {getSourceCollect} from "@/api/customer/source";
import {getGroupCollect} from "@/api/customer/group";

export default {
  name: "Edit",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: '',
    closeAction: '',
  },
  data() {
    return {
      info: {},
      tempData: {
        name: '',
        desc: '',
        diyGroupId: '',
        from: '',
        url: '',
      },
      fromOptions: [
        {label: '全球搜索', value: 1,disabled:!Boolean(this.id)},
        {label: '数据营销', value: 2},
        {label: '外部导入', value: 0},
      ],
      sourceOptions: [],
      groupOptions: [],
      dialogVisible: this.show,
      infoLoading: false,
      isChange: false,
      initForm: false,
      rules: {
        name: [{required: true, message: '请填写标题', trigger: 'blur'}],
        from: [{required: true, message: '请选择类型', trigger: 'blur'}],
      },
    }
  },
  methods: {
    async open(){
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.infoLoading = true;
      if (this.id != '') {
        const {data} = await getBlock(this.id)
        if (data.diyGroupId == 0) {
          data.diyGroupId = ''
        }
        if (data.sourceId == 0) {
          data.sourceId = ''
        }
        this.info = data
      }else{
        this.resetTempData()
        this.info = this.tempData
      }
      this.initForm = true

      //获取来源
      await getSourceCollect().then((res) => {
        this.sourceOptions = res.data
      })
      //获取分组
      await getGroupCollect().then((res) => {
        this.groupOptions = res.data
      })
      setTimeout(() => {
        this.infoLoading = false
      }, 0.5 * 1000)
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm('您有未保存的修改，确定关闭此页吗？', '提示', {
          type: 'warning'
        })
          .then(_ => {
            this.$emit('update:show', false)
          })
          .catch(_ => {
          })
      } else {
        this.$emit('update:show', false)
      }
    },
    resetTempData() {
      this.tempData = {
        name: '',
        desc: '',
        linkedinUrl: '',
        diyGroupId: '',
        from: '',
        url: '',
      }
    },
    subInfo(){
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.infoLoading = true
          let data = this.info
          if (data.groupId == '') {
            data.groupId = 0
          }
          if (data.sourceId == '') {
            data.sourceId = 0
          }
          if (this.id != '') {
            await updateBlock(this.id, data).then((res) => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('closeAction')
            }).catch(() => {
              setTimeout(() => {
                this.infoLoading = false
              }, 0.5 * 1000)
            })
          }else{
            await createBlock(data).then((res) => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('closeAction')
            }).catch(() => {
              setTimeout(() => {
                this.infoLoading = false
              }, 0.5 * 1000)
            })
          }
        }
      })
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
    },
    tempData: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.form-scrollbar {
  height: 450px !important;
}
</style>
